<template>
  <DraggableModal :visible="props.showModal" style="height: 600px" width="600px" :title="`${props.title}角色`" :maskClosable="true" @ok="modalOkFn" @cancel="modalCancelFn">
    <Form ref="formRef" :model="state.data" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="用户名" name="name">
        <Input v-model:value="state.data.name" />
      </a-form-item>
      <a-form-item label="角色" name="description">
        <Tree v-model:checkedKeys="state.checkedKeys" checkable :fieldNames="{ children: 'children', title: 'memo', key: 'id' }" :tree-data="roleTree" />
      </a-form-item>
    </Form>
  </DraggableModal>
</template>

<script setup lang="ts">
import { DraggableModal } from '@/framework/components/core/draggable-modal';
import { message, Form, Input, Tree } from 'ant-design-vue';
import { reactive, ref, watch } from 'vue';
import { getCache, roleAdd, roleUpdate } from '@/api/role-data';
import { roleTree } from '@/modules/platform-management/pages/role-management/columns';
/**
 * const
 */
const props = withDefaults(
  defineProps<{
    showModal?: boolean;
    data: any;
    title: string;
  }>(),
  {
    showModal: false,
  },
);
watch(
  () => props.showModal,
  () => {
    if (props.showModal) {
      state.data = props.data;
      state.checkedKeys = props.data.description?.split(',');
    }
  },
);
const emits = defineEmits<{
  (e: 'update:showModal', state: boolean): void;
  (e: 'editModalOk'): void;
}>();
const formRef = ref();

/**
 * data
 */
const state: {
  data: any;
  checkedKeys: any[];
} = reactive({
  data: {},
  checkedKeys: [],
});
const rules = {
  name: [{ required: true, message: '数据必填!' }],
  description: [{ required: true, message: '数据必填!' }],
};

/**
 * fn
 */
const modalOkFn = async () => {
  // 首层数据处理
  let value = state.checkedKeys;
  value.forEach((item, index) => {
    if (roleTree.value?.map((sub) => sub.id).includes(item)) {
      value.splice(index, 1);
    }
  });
  state.data.description = value.join();
  try {
    await formRef.value?.validateFields();
  } catch {
    return;
  }
  let params: any = {
    name: state.data.name,
    description: state.data.description,
  };

  if (props.title === '新增') {
    await roleAdd(params);
  } else {
    params.id = state.data.id;
    await roleUpdate(params);
    await getCache();
    location.reload();
  }
  message.success('操作成功！');
  emits('editModalOk');
  modalCancelFn();
};
const modalCancelFn = () => {
  formRef.value?.resetFields();
  state.checkedKeys = [];
  state.data = {};
  emits('update:showModal', false);
};
</script>

<style scoped></style>
